package com.bcmusic.music.service.impl;

import com.bcmusic.authorization.feign.AuthorizationFeign;
import com.bcmusic.authorization.pojo.Authorization;
import com.bcmusic.music.dao.MusicMapper;
import com.bcmusic.music.dao.MusicPermissionMapper;
import com.bcmusic.music.domain.music.vo.CertificateVO;
import com.bcmusic.music.domain.permission.dto.AddPermissionDTO;
import com.bcmusic.music.domain.permission.dto.AddTransferDTO;
import com.bcmusic.music.domain.permission.vo.*;
import com.bcmusic.music.pojo.Music;
import com.bcmusic.music.pojo.MusicPermission;
import com.bcmusic.music.service.MusicPermissionService;
import com.bcmusic.music.service.MusicService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import entity.DateUtil;
import entity.SmartBeanUtil;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.test.annotation.Rollback;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.xmlunit.util.Mapper;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/****
 * @Author:admin
 * @Description:MusicPermission业务层接口实现类
 * @Date 2019/6/14 0:16
 *****/
@Service
public class MusicPermissionServiceImpl implements MusicPermissionService {

    @Autowired
    private AuthorizationFeign authorizationFeign;

    @Autowired
    private MusicPermissionMapper musicPermissionMapper;

    @Autowired
    private MusicMapper musicMapper;

    //咳咳，这样做其实是不规范滴
    @Autowired
    private MusicService musicService;
    /**
     * MusicPermission条件+分页查询
     * @param musicPermission 查询条件
     * @param page 页码
     * @param size 页大小
     * @return 分页结果
     */
    @Override
    public PageInfo<MusicPermission> findPage(MusicPermission musicPermission, int page, int size){
        //分页
        PageHelper.startPage(page,size);
        //搜索条件构建
        Example example = createExample(musicPermission);
        //执行搜索
        return new PageInfo<MusicPermission>(musicPermissionMapper.selectByExample(example));
    }

    /**
     * MusicPermission分页查询
     * @param page
     * @param size
     * @return
     */
    @Override
    public PageInfo<MusicPermission> findPage(int page, int size){
        //静态分页
        PageHelper.startPage(page,size);
        //分页查询
        return new PageInfo<MusicPermission>(musicPermissionMapper.selectAll());
    }

    /**
     * MusicPermission条件查询
     * @param musicPermission
     * @return
     */
    @Override
    public List<MusicPermission> findList(MusicPermission musicPermission){
        //构建查询条件
        Example example = createExample(musicPermission);
        //根据构建的条件查询数据
        return musicPermissionMapper.selectByExample(example);
    }


    /**
     * MusicPermission构建查询对象
     * @param musicPermission
     * @return
     */
    public Example createExample(MusicPermission musicPermission){
        Example example=new Example(MusicPermission.class);
        Example.Criteria criteria = example.createCriteria();
        if(musicPermission!=null){
            // 音乐发布信息id。
            if(!StringUtils.isEmpty(musicPermission.getPermissionId())){
                    criteria.andEqualTo("permissionId",musicPermission.getPermissionId());
            }
            // 音乐id
            if(!StringUtils.isEmpty(musicPermission.getMusicId())){
                    criteria.andEqualTo("musicId",musicPermission.getMusicId());
            }
            // 拥有者名单
            if(!StringUtils.isEmpty(musicPermission.getOwnerNumber())){
                    criteria.andEqualTo("ownerNumber",musicPermission.getOwnerNumber());
            }
            // 0为许可，1为转让，3为分发
            if(!StringUtils.isEmpty(musicPermission.getType())){
                    criteria.andEqualTo("type",musicPermission.getType());
            }
            // 允许授权的类型。
            if(!StringUtils.isEmpty(musicPermission.getAllowType())){
                    criteria.andEqualTo("allowType",musicPermission.getAllowType());
            }
            // 允许授权的区域。即版权方允许该音乐授权到哪些区域。（暂定）00为允许国内地区，01为允许国外地区，02为两者均允许。
            if(!StringUtils.isEmpty(musicPermission.getAllowRegion())){
                    criteria.andEqualTo("allowRegion",musicPermission.getAllowRegion());
            }
            // 允许授权开始的时间。即版权方允许该音乐从什么时候开始可授权给被授权方。默认为发布信息提交的时间。
            if(!StringUtils.isEmpty(musicPermission.getAllowStartTime())){
                    criteria.andEqualTo("allowStartTime",musicPermission.getAllowStartTime());
            }
            // 允许授权结束的时间。即版权方允许该音乐授权给被授权方的截止时间。不得早于发布信息提交的时间。
            if(!StringUtils.isEmpty(musicPermission.getAllowEndTime())){
                    criteria.andEqualTo("allowEndTime",musicPermission.getAllowEndTime());
            }
            // 授权单价（元/天）。
            if(!StringUtils.isEmpty(musicPermission.getPricePerDay())){
                    criteria.andEqualTo("pricePerDay",musicPermission.getPricePerDay());
            }
            // 0 表示不允许，1表示允许
            if(!StringUtils.isEmpty(musicPermission.getIsPerpetual())){
                    criteria.andEqualTo("isPerpetual",musicPermission.getIsPerpetual());
            }
            // 永久授权单价（单项）
            if(!StringUtils.isEmpty(musicPermission.getPerpetualPrice())){
                    criteria.andEqualTo("perpetualPrice",musicPermission.getPerpetualPrice());
            }
            // 分发商数量，只有类型是3的时候有效
            if(!StringUtils.isEmpty(musicPermission.getDistributorsNum())){
                    criteria.andEqualTo("distributorsNum",musicPermission.getDistributorsNum());
            }
            // 音乐发布状态。0默认为待审核，1为已发布，-1为审核不通过，-2为已过期，-3为已撤销。
            if(!StringUtils.isEmpty(musicPermission.getValidStatus())){
                    criteria.andEqualTo("validStatus",musicPermission.getValidStatus());
            }
            // 提交时间。默认为提交音乐发布申请的时间。
            if(!StringUtils.isEmpty(musicPermission.getSubmitTime())){
                    criteria.andEqualTo("submitTime",musicPermission.getSubmitTime());
            }
            // 审核时间。即管理员审核音乐发布信息的时间。
            if(!StringUtils.isEmpty(musicPermission.getCheckTime())){
                    criteria.andEqualTo("checkTime",musicPermission.getCheckTime());
            }
            // 审核者编号。即审核音乐发布申请的管理员的编号。此处为任意类型的管理员。
            if(!StringUtils.isEmpty(musicPermission.getAuditorNumber())){
                    criteria.andEqualTo("auditorNumber",musicPermission.getAuditorNumber());
            }
            //
            if(!StringUtils.isEmpty(musicPermission.getModificationTime())){
                    criteria.andEqualTo("modificationTime",musicPermission.getModificationTime());
            }
        }
        return example;
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void delete(Integer id){
        musicPermissionMapper.deleteByPrimaryKey(id);
    }

    /**
     * 修改MusicPermission
     * @param musicPermission
     */
    @Override
    public void update(MusicPermission musicPermission){
        musicPermissionMapper.updateByPrimaryKey(musicPermission);
    }

    /**
     * 增加MusicPermission
     * @param musicPermission
     */
    @Override
    public void add(MusicPermission musicPermission){
        musicPermissionMapper.insert(musicPermission);
    }

    /**
     * 根据ID查询MusicPermission
     * @param id
     * @return
     */
    @Override
    public MusicPermission findById(Integer id){
        return  musicPermissionMapper.selectByPrimaryKey(id);
    }

    /**
     * 查询MusicPermission全部数据
     * @return
     */
    @Override
    public List<MusicPermission> findAll() {
        return musicPermissionMapper.selectAll();
    }



    @Override
    @Rollback
    public int addPermission(AddPermissionDTO addPermissionDTO,String userNum) {
        //直接传参数莫名其妙变成1
        int type=0;
        if(check(addPermissionDTO.getMusicId(),type)==0){
            return 0;
        }
        Music music=musicMapper.selectByPrimaryKey(addPermissionDTO.getMusicId());
        //音乐不存在或者非版权方
        if(music==null||!music.getOwnerNumber().equals(userNum)){
            return 0;
        }
        MusicPermission musicPermission = SmartBeanUtil.copy(addPermissionDTO,MusicPermission.class);

        musicPermission.setAllowType(Arrays.toString(addPermissionDTO.getAllowType()));
        musicPermission.setSubmitTime(new Date());
        musicPermission.setOwnerNumber(music.getOwnerNumber());
        return musicPermissionMapper.insertSelective(musicPermission);
    }

    /**
     * 目前只考虑发布的情况，后面加。
     * @param musicId
     * @param type
     * @return
     */
    @Override
    public int check(Integer musicId, Integer type) {
        MusicPermission musicPermission=new MusicPermission();
        musicPermission.setMusicId(musicId);
        musicPermission.setType(type);
        musicPermission.setValidStatus(1);
        Example example=createCheckExample(musicPermission);
        List<MusicPermission> musicPermissions = musicPermissionMapper.selectByExample(example);
        //证明有发布的
        if(musicPermissions.size()==0){
            return 1;
        }else {
            return 0;
        }
    }

    @Rollback
    @Override
    public int backOut(Integer musicId,List<Integer> backOutList, String userNum) {
        Music music = musicMapper.selectByPrimaryKey(musicId);
        if(music==null||!music.getOwnerNumber().equals(userNum)){
            return 0;
        }
        for (int i = 0; i < backOutList.size(); i++) {
            if(backOutList.get(i)==1){
                MusicPermission musicPermission=new MusicPermission();
                musicPermission.setOwnerNumber(userNum);
                musicPermission.setType(i);
                musicPermission.setValidStatus(1);
                Example example=createCheckExample(musicPermission);
                List<MusicPermission> musicPermissions = musicPermissionMapper.selectByExample(example);
                if(musicPermissions.size()==0){
                }else {
                    musicPermissions.get(0).setValidStatus(-3);
                    int num = musicPermissionMapper.updateByPrimaryKeySelective(musicPermissions.get(0));
                    if(num==0){
                        return 0;
                    }
                }
            }
        }
        return 1;
    }

    /**
     * 获取商品列表
     * @param page
     * @param size
     * @return
     */
    @Override
    public List<MarkerOfMusicVO> getMarketOfMusic(Integer page, Integer size) {

        if(page<=0){
            page=1;
        }
        //分组查询获取其前十首音乐的id
        List<Integer> musicIdList = musicPermissionMapper.findMusicIdList((page - 1) * size, size);
        if(musicIdList.size()==0){
            return null;
        }
        //查询发布信息十首音乐的发布信息，并且将相同musicId的音乐合并
        List<MusicPermission> musicPermissionByMusicIdList = musicPermissionMapper.findMusicPermissionByMusicIdList(musicIdList);

        List<MarkerOfMusicVO>values=new ArrayList<>();
        //合并
        List<Integer> idList=new ArrayList<>();
        for (MusicPermission musicPermission : musicPermissionByMusicIdList) {
            if (!idList.contains(musicPermission.getMusicId())) {
                MarkerOfMusicVO copy = SmartBeanUtil.copy(musicPermission, MarkerOfMusicVO.class);
                values.add(copy);
                idList.add(musicPermission.getMusicId());
            } else {
                for (MarkerOfMusicVO value : values) {
                    if (value.getMusicId().equals(musicPermission.getMusicId())) {
                        value.setType(3);
                    }
                }
            }
        }
        List<CertificateVO> musicInfo = musicService.getMusicInfo(musicIdList);
        for (int i = 0; i < musicInfo.size(); i++) {
            SmartBeanUtil.copyProperties(musicInfo.get(i),values.get(i));
        }
        return values;
    }

    /**
     * 获取转让或者授权信息详情
     * @param musicId
     * @return
     */
    @Override
    public PerMissionDetailVO getMusicPermissionDetail(Integer musicId) {
        MusicPermission musicPermissionDetail = musicPermissionMapper.getMusicPermissionDetail(musicId, 0);
        if(musicPermissionDetail==null){
            return null;
        }else {
            PerMissionDetailVO copy = SmartBeanUtil.copy(musicPermissionDetail, PerMissionDetailVO.class);
            Stack<String> permissionType = toStack(musicPermissionDetail.getAllowType());
            //TODO 不知道这样有木有bug
            String[] array = new String[0];
            copy.setAllowType(permissionType.toArray(array));
            return copy;
        }
    }

    @Override
    public List<DistributionOfMusic> getDistributionOfMusic(Integer page, Integer size) {
        return null;
    }


    @Override
    public int addTransfer(AddTransferDTO addTransferDTO, String userNum) {
        Music music = musicMapper.selectByPrimaryKey(addTransferDTO.getMusicId());
        //音乐不存在或者被其他人恶意调用接口
        if(music==null||!music.getOwnerNumber().equals(userNum)){
            return 0;
        }
        MusicPermission musicTranfer = musicPermissionMapper.getMusicTranfer(music.getMusicId());
        //已有发布信息
        if(musicTranfer!=null){
            return 2;
        }
        List<Authorization> data = authorizationFeign.getCurrentTransferById(music.getMusicId()).getData();
        for (Authorization datum : data) {
            Stack<String> permissionTypes = toStack(datum.getAllowType());
            for (int j = 0; j < addTransferDTO.getAllowType().length; j++) {
                if (permissionTypes.contains(addTransferDTO.getAllowType()[j])) {
                    //存在已经卖出的权限,如果时间冲突就不行
                    if (DateUtil.isContain(datum.getAuthorizationStartTime(), datum.getAuthorizationEndTime(), addTransferDTO.getAllowStartTime(), addTransferDTO.getAllowEndTime())) {
                        return 3;
                    }
                }
            }
        }
        MusicPermission permission = SmartBeanUtil.copy(addTransferDTO, MusicPermission.class);
        permission.setOwnerNumber(userNum);
        permission.setType(1);
        //先设定为有效，目前没有审核模块
        permission.setValidStatus(1);
        return musicPermissionMapper.insertSelective(permission);
    }

    @Override
    public TransferDetailVO getTransferDetail(Integer musicId) {
        MusicPermission musicPermissionDetail = musicPermissionMapper.getMusicPermissionDetail(musicId, 1);
        if(musicPermissionDetail==null){
            return null;
        }
        TransferDetailVO copy = SmartBeanUtil.copy(musicPermissionDetail, TransferDetailVO.class);
        Stack<String> permissionType = toStack(musicPermissionDetail.getAllowType());
        String[] array = new String[0];

        copy.setAllowType(permissionType.toArray(array));
        return copy;
    }

    @Override
    public List<GetDateVO> getTransTime(Integer musicId, List<String> typeList) {
        MusicPermission musicPermissionDetail = musicPermissionMapper.getMusicPermissionDetail(musicId, 1);
        if(musicPermissionDetail==null){
            return null;
        }
        List<Authorization> list = authorizationFeign.getCurrentTransferById(musicId).getData();
        List<GetDateVO>timeList=new ArrayList<>();
        for(Authorization transfer:list){

            Stack<String> boughtPermission = toStack(transfer.getAllowType());
            for (String s : typeList) {
                if (boughtPermission.contains(s)) {
                    GetDateVO getDateVO = new GetDateVO();
                    getDateVO.setStartDate(transfer.getAuthorizationStartTime());
                    getDateVO.setStartDate(transfer.getAuthorizationEndTime());
                    timeList.add(getDateVO);
                    break;
                }
            }
        }
        return timeList;
    }


    public Example createCheckExample(MusicPermission musicPermission){
        Example example=new Example(MusicPermission.class);
        Example.Criteria criteria = example.createCriteria();
        if(musicPermission!=null){
            // 音乐id
            if(!StringUtils.isEmpty(musicPermission.getMusicId())){
                criteria.andEqualTo("musicId",musicPermission.getMusicId());
            }
            // 0为许可，1为转让，3为分发
            if(!StringUtils.isEmpty(musicPermission.getType())){
                criteria.andEqualTo("type",musicPermission.getType());
            }
            // 音乐发布状态。0默认为待审核，1为已发布，-1为审核不通过，-2为已过期，-3为已撤销。
            if(!StringUtils.isEmpty(musicPermission.getValidStatus())){
                //0，1都不可再发布
                criteria.andBetween("validStatus",0,1);
            }
            // 提交时间。默认为提交音乐发布申请的时间。
        }
        return example;
    }

    /**
     * 将版权信息转换为stack校验
     * @param s
     * @return
     */
    public Stack<String> toStack(String s){
        if(s==null){
            return null;
        }
        StringBuilder stringBuilder=new StringBuilder(s);
        stringBuilder.delete(0,1);
        stringBuilder.delete(stringBuilder.length()-1,stringBuilder.length());
        String []s1=stringBuilder.toString().split(",");
        if(s1.length==0|| "".equals(s1[0])){
            return null;
        }
        Stack<String> stack=new Stack<>();
        Collections.addAll(stack, s1);
        return stack;
    }

}
